"""
>>> f = compiler.compile(T.path)
>>> f('example/xxx.log') == os.path.join(os.getcwd(), 'example/xxx.log')
True
>>> f = compiler.compile(T.str_list)
>>> f('a, b, c')
['a', 'b', 'c']
>>> f(['xx', 'yy'])
['xx', 'yy']
>>> f(' ')
[]
>>> f = compiler.compile(T.timer)
>>> f('60s')
'60s'
"""
import os.path
import logging

from validr import T, Compiler, Invalid, validator

from .timer import Timer


LOG = logging.getLogger(__name__)


@validator(accept=str, output=str)
def path_validator(compiler):
    def validate(value):
        return os.path.abspath(os.path.expanduser(value))
    return validate


@validator(accept=(str, object), output=object)
def str_list_validator(compiler):

    validate_items = compiler.compile(T.list(T.str))

    def validate(value):
        if isinstance(value, (tuple, list, set)):
            return validate_items(value)
        value = value.replace(',', ' ').strip()
        if not value:
            return []
        return list(value.split())

    return validate


@validator(accept=(str, object), output=str)
def timer_validator(compiler, output_object=False):
    def validate(value):
        if not Timer.is_valid(value):
            raise Invalid('invalid timer expression')
        return value
    return validate


compiler = Compiler(validators=dict(
    path=path_validator,
    str_list=str_list_validator,
    timer=timer_validator,
))
